package com.example.common.config;

import com.example.common.utils.*;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.*;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.*;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.serializer.RedisSerializationContext.SerializationPair;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.cache.CacheManager;
import java.time.Duration;

@Configuration
@EnableCaching
public class RedisConfig {
    
    @Bean
    public Jackson2JsonRedisSerializer<Object> jacksonSerializer() {
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        serializer.setObjectMapper(JsonUtil.getMapper());
        return serializer;
    }
    
    /**
     * Redis连接配置 - 可自定义主机、端口、密码
     */
    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        config.setHostName("localhost");  // 修改为Redis地址
        config.setPort(6379);
        // config.setPassword(RedisPassword.of("your-password")); // 如果有密码
        return new LettuceConnectionFactory(config);
    }
    
    /**
     * 用于操作String类型的Redis模板
     */
    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
        return new StringRedisTemplate(factory);
    }
    
    /**
     * 通用的Redis模板，使用JSON进行序列化
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        
        // 设置序列化器
        setSerializer(template);
        
        template.afterPropertiesSet();
        return template;
    }
    
    /**
     * 配置RedisTemplate的序列化方式：使用String序列化Key，JSON序列化Value
     */
    private void setSerializer(RedisTemplate<String, Object> template) {
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer<Object> jsonSerializer = jacksonSerializer();
        
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(jsonSerializer);
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jsonSerializer);
    }
    
    /**
     * Spring Cache使用的CacheManager
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                                             .entryTtl(Duration.ofHours(1)) // 默认缓存1小时
                                             .serializeKeysWith(
                                                 SerializationPair
                                                     .fromSerializer(new StringRedisSerializer())
                                             )
                                             .serializeValuesWith(
                                                 SerializationPair
                                                     .fromSerializer(jacksonSerializer())
                                             )
                                             .disableCachingNullValues();
        
        return RedisCacheManager.builder(connectionFactory)
                   .cacheDefaults(config)
                   .build();
    }
}
